package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.Page;
import com.github.pagehelper.page.PageMethod;
import com.sky.constant.MessageConstant;
import com.sky.context.BaseContext;
import com.sky.dto.*;
import com.sky.entity.AddressBook;
import com.sky.entity.OrderDetail;
import com.sky.entity.Orders;
import com.sky.entity.ShoppingCart;
import com.sky.exception.OrderBusinessException;
import com.sky.mapper.*;
import com.sky.result.PageResult;
import com.sky.service.OrdersService;
import com.sky.utils.HttpClientUtil;
import com.sky.utils.WeChatPayUtil;
import com.sky.vo.OrderPaymentVO;
import com.sky.vo.OrderStatisticsVO;
import com.sky.vo.OrderSubmitVO;
import com.sky.vo.OrderVO;
import com.sky.websocket.WebSocketServer;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * Author: Zheng
 * Date:   2024/2/26  9:49
 * Package：com.sky.service.impl
 * Description：
 * Version：1.0
 */
@Service
@Slf4j
public class OrdersServiceImpl implements OrdersService {

    @Value("${sky.shop.address}")
    private String shopAddress;//店铺地址
    @Value("${sky.shop.ak}")
    private String ak;//百度地图应用服务ak
    @Value("${sky.shop.distance}")
    private Integer distance;//配送距离上限

    //地理编码接口，获取地址的经纬度坐标
    private static final String GEO_CODING_URL = "https://api.map.baidu.com/geocoding/v3/";
    //路线规划接口，骑行路线规划，（可以视业务情况选择骑行、公交、驾车等路线，接口不一样，可以配置在yml中）
    private static final String DIRECTION_URL = "https://api.map.baidu.com/directionlite/v1/riding";

    @Autowired
    private OrdersMapper ordersMapper;
    @Autowired
    private AddressBookMapper addressBookMapper;
    @Autowired
    private ShoppingCartMapper shoppingCartMapper;
    @Autowired
    private OrderDetailMapper orderDetailMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private WeChatPayUtil weChatPayUtil;
    @Autowired
    private WebSocketServer webSocketServer;

    /**
     * @param ordersSubmitDTO
     * @description： 用户下单
     * @date：2024/2/26 16:14
     * @return：
     */
    @Override
    @Transactional //开启事务
    public OrderSubmitVO submit(OrdersSubmitDTO ordersSubmitDTO) {

        //构造订单数据
        Orders orders = new Orders();
        BeanUtils.copyProperties(ordersSubmitDTO, orders);

        //获取当前用户id
        Long userId = BaseContext.getCurrentId();

        //根据地址id获取地址
        AddressBook addressBook = addressBookMapper.getById(ordersSubmitDTO.getAddressBookId());
        if (addressBook == null) {
            throw new OrderBusinessException(MessageConstant.ADDRESS_BOOK_IS_NULL);
        }
        if (!checkOutOfRange(addressBook.getProvinceName()+addressBook.getCityName()+addressBook.getDistrictName()+addressBook.getDetail())){
            throw new OrderBusinessException(MessageConstant.OUT_OF_RANGE);
        }

            //订单号
            orders.setNumber(String.valueOf(System.currentTimeMillis()));
        //订单状态
        orders.setStatus(Orders.PENDING_PAYMENT);//待付款
        //用户id
        orders.setUserId(userId);
        //下单时间
        orders.setOrderTime(LocalDateTime.now());
        //支付方式
        orders.setPayMethod(1);//未支付
        //支付状态
        orders.setPayStatus(Orders.UN_PAID);
        //地址
        orders.setAddress(addressBook.getDetail());
        //收货人
        orders.setConsignee(addressBook.getConsignee());
        //手机号
        orders.setPhone(addressBook.getPhone());
        //将订单数据插入到orders表中
        ordersMapper.insert(orders);

        //构造订单明细表
        List<ShoppingCart> carts = shoppingCartMapper.getByUserId(userId);
        if (carts == null) {
            throw new OrderBusinessException(MessageConstant.SHOPPING_CART_IS_NULL);
        }
        List<OrderDetail> orderDetails = new ArrayList<>();
        carts.forEach(cart -> {
            OrderDetail orderDetail = new OrderDetail();
            BeanUtils.copyProperties(cart, orderDetail, "id");
            orderDetail.setOrderId(orders.getId());
            orderDetails.add(orderDetail);
        });

        orderDetailMapper.insertBatch(orderDetails);
        shoppingCartMapper.deleteByUserId(userId);

        return OrderSubmitVO.builder()
                .id(orders.getId())
                .orderNumber(orders.getNumber())
                .orderAmount(orders.getAmount())
                .orderTime(orders.getOrderTime())
                .build();
    }

    /**
     * @description： 校验配送范围
     * @date：2024/2/29 15:46
     * @return：
     **/
    private boolean checkOutOfRange(String address) {
        //1.获取店铺的地址坐标
        //https://api.map.baidu.com/geocoding/v3/?address=北京市海淀区上地十街10号&output=json&ak=您的ak
        Map<String, String> paramMap = new HashMap<>();
        paramMap.put("address", this.shopAddress);
        paramMap.put("output", "json");
        paramMap.put("ak", this.ak);
        String jsonStr = HttpClientUtil.doGet(GEO_CODING_URL, paramMap);
        JSONObject jsonObject = JSON.parseObject(jsonStr);
        if (!jsonObject.get("status").equals(0)) {
            throw new OrderBusinessException(MessageConstant.ADDRESS_PARSE_FAILED);//地址解析失败
        }
        JSONObject jsonObject1 = jsonObject.getJSONObject("result").getJSONObject("location");
        Object lng = jsonObject1.get("lng");//经度
        Object lat = jsonObject1.get("lat");//纬度
        String origin = lat + "," + lng;
        log.info("店铺坐标：{}", origin);

        //获取收货地址坐标
        paramMap.put("address", address);
        jsonStr = HttpClientUtil.doGet(GEO_CODING_URL, paramMap);
        jsonObject = JSON.parseObject(jsonStr);
        if (!jsonObject.get("status").equals(0)){
            throw new OrderBusinessException(MessageConstant.ADDRESS_PARSE_FAILED);
        }
        jsonObject1 = jsonObject.getJSONObject("result").getJSONObject("location");
        lng = jsonObject1.get("lng");//经度
        lat = jsonObject1.get("lat");//纬度
        String destination = lat + "," +lng;
        log.info("收获地址的坐标：{}",destination);

        //3.根据店铺和收货地址坐标，进行距离计算，如果超出5公里，就返回false
        //https://api.map.baidu.com/directionlite/v1/riding?origin=40.01116,116.339303&destination=39.936404,116.452562&ak=您的AK
        paramMap.put("origin", origin);
        paramMap.put("destination", destination);
        jsonStr = HttpClientUtil.doGet(DIRECTION_URL, paramMap);
        jsonObject = JSON.parseObject(jsonStr);
        if (!jsonObject.get("status").equals(0)){
            throw new OrderBusinessException(MessageConstant.ADDRESS_PARSE_FAILED);
        }
        JSONArray routes = jsonObject.getJSONObject("result").getJSONArray("routes");
        Integer distance = (Integer) routes.getJSONObject(0).get("distance");
        log.info("配送距离：{}米",distance);

        return distance <= this.distance;
    }

    /**
     * @param ordersPaymentDTO
     * @description： 订单支付
     * @date：2024/2/27 20:22
     * @return：
     */
    @Override
    public OrderPaymentVO payment(OrdersPaymentDTO ordersPaymentDTO) {
        ////当前用户id
        //Long userId = BaseContext.getCurrentId();
        //User user = userMapper.getById(userId);
        //
        //JSONObject jsonObject;
        ////调用微信支付接口，生成预交易单
        //try {
        //     jsonObject = weChatPayUtil.pay(
        //            ordersPaymentDTO.getOrderNumber(),//商户订单号
        //            new BigDecimal(0.01),//支付金额，单位：元
        //            "苍穹外卖订单",//商品描述
        //            user.getOpenid()//微信用户openid
        //    );
        //} catch (Exception e) {
        //    throw new OrderBusinessException("支付接口异常！");
        //}
        //
        //if (jsonObject.getString("code") != null && jsonObject.getString("code").equals("ORDERPAID")){
        //    throw new OrderBusinessException("订单已支付！");
        //}
        //OrderPaymentVO orderPaymentVO = jsonObject.toJavaObject(OrderPaymentVO.class);

        // OrderPaymentVO vo = jsonObject.toJavaObject(OrderPaymentVO.class);
        // vo.setPackageStr(jsonObject.getString("package"));

        //由于没有匹配的商户id，所以微信支付并不能调用成功，为了模拟成功的，所以直接返回成功结果，但是需要修改订单状态
        //订单状态：修改为待接单，支付状态：已支付
        paySuccess(ordersPaymentDTO.getOrderNumber());

        return new OrderPaymentVO();
    }

    /**
     * @description： 返回支付成功
     * @date：2024/2/27 22:41
     * @return：
     **/
    public void paySuccess(String outTradeNo) {
        //当前登录用户id
        Long userId = BaseContext.getCurrentId();

        //根据订单号查询当前用户订单
        Orders ordersDB = ordersMapper.getByNumberAndUserID(outTradeNo, userId);

        //根据订单id更新订单状态，支付方式，支付状态，结账时间
        Orders orders = Orders.builder()
                .id(ordersDB.getId())
                .status(Orders.TO_BE_CONFIRMED) //订单状态：修改为待接单
                .payStatus(Orders.PAID)         //支付状态：修改为已支付
                .checkoutTime(LocalDateTime.now())
                .build();
        ordersMapper.update(orders);

        Map map = new HashMap<>();

        map.put("type", 1);//消息类型，1表示来单提醒
        map.put("orderId", orders.getId());//订单id
        map.put("content", "订单号：" + outTradeNo);
        //通过websocket实现来单提醒，向客户端浏览器推送消息
        webSocketServer.sendToAllClient(JSON.toJSONString(map));
    }

    /**
     * @param ordersPageQueryDTO
     * @description： 历史订单查询
     * @date：2024/2/27 20:33
     * @return：
     */
    @Override
    public PageResult page(OrdersPageQueryDTO ordersPageQueryDTO) {
        PageMethod.startPage(ordersPageQueryDTO.getPage(), ordersPageQueryDTO.getPageSize());
        Long userId = BaseContext.getCurrentId();
        ordersPageQueryDTO.setUserId(userId);

        //分页条件查询
        Page<Orders> pages = ordersMapper.page(ordersPageQueryDTO);

        List<OrderVO> orderVOList = new ArrayList<>();

        if (pages == null && pages.getTotal() == 0) {
            return null;
        }
        //查询订单明细，封装进OrderVO
        pages.forEach(order -> {
            Long orderId = order.getId();
            List<OrderDetail> orderDetailList = orderDetailMapper.getByOrderId(orderId);
            OrderVO orderVO = new OrderVO();
            BeanUtils.copyProperties(order, orderVO);
            orderVO.setOrderDetailList(orderDetailList);
            orderVOList.add(orderVO);
        });
        return new PageResult(pages.getTotal(), orderVOList);
    }


    /**
     * @param id
     * @description： 订单详情查询
     * @date：2024/2/27 20:37
     * @return：
     */
    @Override
    public OrderVO details(Long id) {
        //根据id查询订单
        Orders orders = ordersMapper.getById(id);
        //查询该订单对象的菜品、套餐明细
        List<OrderDetail> detailList = orderDetailMapper.getByOrderId(orders.getId());
        OrderVO orderVO = new OrderVO();
        BeanUtils.copyProperties(orders, orderVO);
        orderVO.setOrderDetailList(detailList);

        return orderVO;
    }

    /**
     * @param id
     * @description： 取消订单
     * @date：2024/2/27 20:41
     * @return：
     */
    @Override
    public void userCancelById(Long id) {
        Orders ordersDB = ordersMapper.getById(id);
        //判断订单是否存在
        if (ordersDB == null) {
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }
        //判断订单是否支付 订单状态 1待付款 2待接单 3已接单 4派送中 5已完成 6已取消
        if (ordersDB.getPayStatus() > 2) {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }
        Orders orders = new Orders();
        orders.setId(ordersDB.getId());

        //订单处于待接单状态下取消，需要进行退款
        if (ordersDB.getStatus().equals(Orders.TO_BE_CONFIRMED)) {
            //调用微信支付退款接口， 由于没有可用商户id，下面的退款操作执行会失败，直接注释，假设退款成功，直接修改状态
            //try {
            //    weChatPayUtil.refund(
            //            ordersDB.getNumber(),//商户id
            //            ordersDB.getNumber(),//商户退款单号
            //            new BigDecimal(0.01),//退款金额，单位：元
            //            new BigDecimal(0.01)//原订单金额
            //    );
            //} catch (Exception e) {
            //    throw new OrderBusinessException("退款接口异常");
            //}
            orders.setPayStatus(Orders.REFUND);
        }

        //更新订单状态，取消原因，取消时间
        orders.setStatus(Orders.CANCELLED);
        orders.setCancelReason("用户取消");
        orders.setCancelTime(LocalDateTime.now());
        ordersMapper.update(orders);

    }

    /**
     * @param ordersPageQueryDTO
     * @description： 管理端订单搜索
     * @date：2024/2/28 17:49
     * @return：
     */
    @Override
    public PageResult conditionSearch(OrdersPageQueryDTO ordersPageQueryDTO) {

        PageMethod.startPage(ordersPageQueryDTO.getPage(), ordersPageQueryDTO.getPageSize());
        Page<Orders> page = ordersMapper.page(ordersPageQueryDTO);
        if (page == null && page.getTotal() == 0) {
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }
        List<OrderVO> orderVOList = getOrderVOList(page);

        return new PageResult(page.getTotal(), orderVOList);
    }

    /**
     * @description： 封装OrderVO，添加到orderVOList
     * @date：2024/2/28 18:19
     * @return：
     **/
    private List<OrderVO> getOrderVOList(Page<Orders> page) {

        //需要返回订单菜品信息，自定义OrderVO响应结果
        List<OrderVO> orderVOList = new ArrayList<>();
        List<Orders> ordersList = page.getResult();

        if (!ordersList.isEmpty()) {
            ordersList.forEach(orders -> {
                OrderVO orderVO = new OrderVO();
                //将共同字段复制到OrderVO
                BeanUtils.copyProperties(orders, orderVO);
                String orderDishes = getOrderDishesStr(orders);
                //将订单菜品信息封装到orderVO中，并添加到orderVOList返回
                orderVO.setOrderDishes(orderDishes);
                orderVOList.add(orderVO);
            });
        }
        return orderVOList;
    }

    /**
     * @description： 根据订单id获取菜品信息字符串
     * @date：2024/2/28 18:15
     * @return：
     **/
    private String getOrderDishesStr(Orders orders) {
        //查询订单菜品详细信息
        List<OrderDetail> detailList = orderDetailMapper.getByOrderId(orders.getId());

        //将每一条订单菜品信息拼接位字符串（菜品名*份数;）
        List<String> orderDishList = detailList.stream().map(orderDetail -> {
            String orderDish = orderDetail.getName() + "*" + orderDetail.getNumber() + ";";
            return orderDish;
        }).collect(Collectors.toList());
        return String.join("", orderDishList);
    }


    /**
     * @param id
     * @description： 再来一单
     * @date：2024/2/27 20:46
     * @return：
     */
    @Override
    public void repetition(Long id) {
        //查询当前用户id
        Long userId = BaseContext.getCurrentId();

        //根据id查询当前订单详情
        List<OrderDetail> detailList = orderDetailMapper.getByOrderId(id);
        detailList.forEach(orderDetail -> {
            ShoppingCart shoppingCart = new ShoppingCart();
            //将原订单详情的菜品复制到购物车对象
            BeanUtils.copyProperties(orderDetail, shoppingCart, "id");
            shoppingCart.setUserId(userId);
            shoppingCart.setCreateTime(LocalDateTime.now());
            shoppingCartMapper.insert(shoppingCart);
        });


    }

    /**
     * @description： 各个状态的订单数量统计
     * @date：2024/2/28 18:47
     * @return：
     **/
    @Override
    public OrderStatisticsVO statistics() {
        //根据状态，分别查询出待接单，待派送，派送中的订单
        Integer toBeConfirmed = ordersMapper.countStatus(Orders.TO_BE_CONFIRMED);
        Integer confirmed = ordersMapper.countStatus(Orders.CONFIRMED);
        Integer deliveryInProgress = ordersMapper.countStatus(Orders.DELIVERY_IN_PROGRESS);

        //将查询出的数据封装到orderStatisticsVO中响应
        OrderStatisticsVO orderStatisticsVO = new OrderStatisticsVO();
        orderStatisticsVO.setConfirmed(confirmed);
        orderStatisticsVO.setToBeConfirmed(toBeConfirmed);
        orderStatisticsVO.setDeliveryInProgress(deliveryInProgress);
        return orderStatisticsVO;
    }

    /**
     * @param ordersConfirmDTO
     * @description： 接单
     * @date：2024/2/28 18:34
     * @return：
     */
    @Override
    public void confirm(OrdersConfirmDTO ordersConfirmDTO) {

        Orders orders = Orders.builder()
                .id(ordersConfirmDTO.getId())
                .status(Orders.CONFIRMED)
                .build();
        ordersMapper.update(orders);
    }

    /**
     * @param ordersRejectionDTO
     * @description： 拒单
     * @date：2024/2/28 20:08
     * @return：
     */
    @Override
    public void rejection(OrdersRejectionDTO ordersRejectionDTO) {
        //根据id查询订单
        Orders orderDB = ordersMapper.getById(ordersRejectionDTO.getId());
        //只有订单存在且状态为2时才可以拒单
        if (orderDB == null || !orderDB.getStatus().equals(Orders.TO_BE_CONFIRMED)) {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }
        Integer payStatus = orderDB.getPayStatus();
        if (payStatus.equals(Orders.PAID)) {
            //用户已支付，需要退款
            //try {
            //    String refund = weChatPayUtil.refund(
            //            orderDB.getNumber(),
            //            orderDB.getNumber(),
            //            new BigDecimal("0.01"),
            //            new BigDecimal("0.01")
            //    );
            //    log.info("申请退款：{}",refund);
            //} catch (Exception e) {
            //    throw new OrderBusinessException("退款接口异常！");
            //}
        }
        //拒单需要退款，根据订单id更新订单状态，拒单原因，取消时间
        Orders orders = Orders.builder()
                .id(orderDB.getId())
                .payStatus(Orders.REFUND)
                .status(Orders.CANCELLED)
                .rejectionReason(ordersRejectionDTO.getRejectionReason())
                .cancelTime(LocalDateTime.now())
                .build();
        ordersMapper.update(orders);
    }

    /**
     * @param ordersCancelDTO
     * @description： 取消订单
     * @date：2024/2/28 21:09
     * @return：
     */
    @Override
    public void cancel(OrdersCancelDTO ordersCancelDTO) {
        //根据id查询订单
        Orders ordersDB = ordersMapper.getById(ordersCancelDTO.getId());

        //支付状态
        Integer payStatus = ordersDB.getPayStatus();


        //用户如果已支付，需要退款
        if (payStatus == 1) {
            //try {
            //    String refund = weChatPayUtil.refund(
            //            orderDB.getNumber(),
            //            orderDB.getNumber(),
            //            new BigDecimal("0.01"),
            //            new BigDecimal("0.01")
            //    );
            //    log.info("申请退款：{}",refund);
            //} catch (Exception e) {
            //    throw new OrderBusinessException("退款接口异常！");
            //}
        }

        // 管理端取消订单需要退款，根据订单id更新订单状态、取消原因、取消时间
        Orders orders = Orders.builder()
                .id(ordersDB.getId())
                .status(Orders.CANCELLED)
                .cancelReason(ordersCancelDTO.getCancelReason())
                .cancelTime(LocalDateTime.now())
                .build();
        ordersMapper.update(orders);
    }

    /**
     * @param id
     * @description： 派送订单
     * @date：2024/2/28 21:25
     * @return：
     */
    @Override
    public void delivery(Long id) {
        //根据订单id查询订单
        Orders ordersDB = ordersMapper.getById(id);

        //校验订单是否存在,并且状态是否为3
        if (ordersDB == null || !ordersDB.getStatus().equals(Orders.CONFIRMED)) {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }

        Orders orders = Orders.builder()
                .id(ordersDB.getId())
                .status(Orders.DELIVERY_IN_PROGRESS)// 更新订单状态为派送中
                .build();
        ordersMapper.update(orders);
    }

    /**
     * @param id
     * @description： 完成订单
     * @date：2024/2/28 21:39
     * @return：
     */
    @Override
    public void complete(Long id) {
        Orders ordersDB = ordersMapper.getById(id);

        if (ordersDB == null || !ordersDB.getStatus().equals(Orders.DELIVERY_IN_PROGRESS)) {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }

        Orders orders = Orders.builder()
                .id(ordersDB.getId())
                .status(Orders.COMPLETED)
                .deliveryTime(LocalDateTime.now())
                .build();
        ordersMapper.update(orders);
    }

    /**
     * @param id
     * @description： 用户催单
     * @date：2024/2/29 14:51
     * @return：
     */
    @Override
    public void reminder(Long id) {
        Orders orders = ordersMapper.getById(id);

        if (orders == null) {
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }

        Map map = new HashMap();
        map.put("type", 2);
        map.put("orderId", id);
        map.put("content", "订单号：" + orders.getNumber());
        webSocketServer.sendToAllClient(JSON.toJSONString(map));
    }
}
